package com.sunkq.algorithms;

import java.util.Scanner;

public class SeatTest {

    private static String seatSign = "00000000000000000000000000000000000000000000000000";

    public static void main(String[] args) {
        System.out.println("当前座位情况：");
        System.out.println(seatSign);
        for (int i = 0; i < 100; i++) {
            Scanner input = new Scanner(System.in);
            System.out.println("请输入操作代码。1：购票，2：退票");
            int flag = input.nextInt();
            if (flag == 1) {
                System.out.println("请输入买票张数:");
                int orderSize = input.nextInt();
                setSeat(orderSize);
                System.out.println("购票 " + orderSize + " 张。当前座位情况：");
                System.out.println(seatSign + "");
            } else if (flag == 2) {
                System.out.println("请输入退票座位号：");
                int seatNo = input.nextInt();
                char[] seatArray = seatSign.toCharArray();
                seatArray[seatNo - 1] = '0';
                seatSign = String.valueOf(seatArray);
                System.out.println("退票1张。当前座位情况：");
                System.out.println(seatSign + "");
            }
        }
    }

    private static void setSeat(int orderSize) {
        char[] seatArray = seatSign.toCharArray();
        // 连续分配Flag
        boolean continuousFlag = true;
        for (int i = 0; i < seatArray.length; i++) {
            continuousFlag = true;
            // 当前座位有人
            if (seatArray[i] == '1') {
                // 遍历一次没能分配连续座位
                if (i == seatArray.length - 1) {
                    continuousFlag = false;
                }
                continue;
            }
            // 当前座位没人，检查接下来的[订单数-1]个座位有没有人
            for (int j = 1; j < orderSize; j++) {
                // 检查到最后一位都没有连续座位
                if (i + j >= seatArray.length) {
                    continuousFlag = false;
                    break;
                }
                if (seatArray[i + j] == '1') {
                    i = i + j;
                    continuousFlag = false;
                    break;
                }
            }
            if (continuousFlag) {
                // 分配连续车票
                for (int k = 0; k < orderSize; k++) {
                    seatArray[i + k] = '1';
                }
                break;
            }
        }
        if (!continuousFlag) {
            // 分配不连续车票
            int seatFlag = 0;
            for (int i = 0; i < orderSize; i++) {
                // boolean currentSeatSuccess = false;
                for (; seatFlag < seatArray.length; seatFlag++) {
                    if (seatArray[seatFlag] == '0') {
                        // 座位占位符数组更新
                        seatArray[seatFlag] = '1';
                        break;
                    }
                }
            }
        }
        seatSign = String.valueOf(seatArray);
    }
}
